//
//  RegistViewController.m
//  Growth
//
//  Created by MEET on 12-1-4.
//  Copyright 2012 MEETStudio. All rights reserved.
//

#import "RegistViewController.h"


@implementation RegistViewController

@synthesize nickNametextField;
@synthesize emailtextField;
@synthesize keytextField;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

//*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	
    self.contentView.backgroundColor = BackGround_Color;
  

    
    //定义返回按钮
    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
    
    [[self navigationItem] setBackBarButtonItem:backBarButtonItem]; 
    self.navigationItem.title = @"注册";
    
    [backBarButtonItem release]; 

    
    [super viewDidLoad];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[nickNametextField release];
	[emailtextField release];
	[keytextField release];
    [super dealloc];
}


#pragma textField delegat
-(void)textFieldDidBeginEditing:(UITextField *)textField{
 
    if (textField.tag == 2) {
        [self verifyNickName:nickNametextField.text];
    }

    
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag ==1) {
        [self verifyNickName:nickNametextField.text];
    }
    if (textField.tag == 2) {
        [self verifyEmail:emailtextField.text];
    }
    
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField.tag == 1) {
        [emailtextField becomeFirstResponder];
    }
    if (textField.tag == 2) {
        [keytextField becomeFirstResponder];
    }
    if (textField.tag == 3) {
        //[self registerAction:nil];
        [textField resignFirstResponder];
    }
    
    return YES;
}

#pragma verify

-(void)verifyNickName:(NSString *)nickName{ //验证nickname
    
    NSMutableURLRequest *request = [WebRequest verifyNickNameRequest:nickName];
    
    CLog(@"request %@", request);
    WebConnectionArray *connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    
}

-(void)verifyEmail:(NSString *)email{
    
    NSMutableURLRequest * request = [WebRequest verifyEmailRequest:email];
    
    CLog(@"request %@", request);
    WebConnectionArray *connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    

    
    
}

#pragma mark -WebConnection delegate

- (void)connectionSuccess:(NSDictionary *)dict{
	
    
}

- (void)connectionError:(NSError *)error{
	
}
- (void)postSuccess:(NSString *)postinfo{
    CLog(@"post info");
    
    
}

- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    
    
     
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/verify/email?email=%@",MYBASEURL, emailtextField.text]])  {
        
         CLog(@"verify email %@",[dict objectForKey:@"object"] );
        
       if ([[dict objectForKey:@"object"] boolValue]== TRUE) { 
           _isEmailCorrect = TRUE;       
                       
            return;
        }
       else{
           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"邮箱验证错误！" 
                                                          delegate:self 
                                                 cancelButtonTitle:@"确定" otherButtonTitles:nil];
           
           [alert show];
           [alert release];
       }

    }
    
    
    // NSString *encodedValue = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/verify/nickname?nickname=%@",MYBASEURL, [nickNametextField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]])  {
        
        CLog(@"verify nickName %@",[dict objectForKey:@"object"] );
        
        if ([[dict objectForKey:@"object"] boolValue]== TRUE) { 
            _isNickNameCorrect = TRUE;       
            
            return;
        }
        else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"该昵称已经被注册啦，换一个吧！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
        
        
    }

    
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/regist",MYBASEURL]])  {
        
        if([dict objectForKey:@"object"]){
            NSDictionary *userInfo = [dict objectForKey:@"object"];
            [[NSUserDefaults standardUserDefaults] setValue:[userInfo objectForKey:@"userId"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] setValue:[userInfo objectForKey:@"User-Code"] forKey:@"User-Code"];
            [[NSUserDefaults standardUserDefaults] setValue:[userInfo objectForKey:@"User-VerifyCode"] forKey:@"User-VerifyCode"];

            [self registerSuccess ];

        }
        
    }
    
       
    
}

- (void)connectionArrayError:(NSError *)error{
	
}



#pragma mark action

- (void)registerSuccess{
	//注册成功，返回登陆界面，并考虑直接跳转登陆 
	
    
    if (self.delegate != nil) {
        
         [self backHome:nil];
        [self.delegate toTimelineSettingView:nil];
       
        
    }
    
}

- (void)registerError{
	//弹出错误提示
}
 
-(IBAction)registerAction:(id)sender{
	//UIButton *button = (UIButton *)sender;
	//button.tag;
    
    if (!_isNickNameCorrect || !_isEmailCorrect) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"昵称或邮箱验证错误！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;    
    }
    if (keytextField.text.length>32 || keytextField.text.length<6) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"密码长度必须为6～32位！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;    

        
    }
    if (nickNametextField.text.length>12) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"昵称不能超过十个字！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;    

        
    }
    
	
    NSArray *keys = [NSArray arrayWithObjects:@"email", @"nickname",@"password", nil];

    
    NSArray *objects;
    objects = [NSArray arrayWithObjects:emailtextField.text, nickNametextField.text,keytextField.text, nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", theBodyString);
    
    
    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest * request = [WebRequest registRequestWith:jsonData];
    
    CLog(@"request %@", request);
    WebConnectionArray *connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    
    
    _isPostRegist = TRUE;

	
	
	//注册成功
	//[self registerSuccess];
}

-(IBAction)backgroundTap:(id)sender{
	[nickNametextField resignFirstResponder];
	[emailtextField resignFirstResponder];
	[keytextField resignFirstResponder];
}

@end
